package com.itboye.mengwu.app.ui.roof;

import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.itboye.config.GlobalConfig;
import com.itboye.core.object.BaseFragment;
import com.itboye.core.object.BasePtr;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.core.utils.XPicasso;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.ui.main.GoodsDetailActivity;
import com.itboye.mengwu.app.ui.web.WebActivity;
import com.itboye.mengwu.data.model.AppHeadPage;
import com.itboye.mengwu.data.model.HomeTypeTwoModel;
import com.itboye.mengwu.data.presenter.HomePagePresenter;
import com.itboye.mengwu.luntan.comment.view.MyListView;

import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;

public class HomePageItemFragmentTypeTwo extends BaseFragment implements
        Observer {

    AppHeadPage page;
    ArrayList<String> imagesList = new ArrayList<String>();
    ArrayList<String> goodsName = new ArrayList<String>();
    ArrayList<String> goodsPrice = new ArrayList<String>();
    ArrayList<String> goodsPid = new ArrayList<String>();
    int pageSize = 0;
    HomePagePresenter homePagePresenter;
    ArrayList<AppHeadPage> arrayList = new ArrayList<AppHeadPage>();
    LinearLayout list;
    ImageView ad_two;
    String adtwo;
    String blokdan2;
    String blok4;
    MyListView mylistview;
    ArrayList<String> bannerNamedan = new ArrayList<String>();
    ArrayList<String> bannerNamedan2 = new ArrayList<String>();
    String APP_URL = "http://www.moodwo.com/index.php/Webview";

    PtrFrameLayout commend_anchor_ptr;
    int posionID;
    private String uid = "";
    private String psw = "";

    public HomePageItemFragmentTypeTwo(int posion) {
        // TODO Auto-generated constructor stub
        this.pageSize = posion;
    }

    public HomePageItemFragmentTypeTwo() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public int initView() {
        // TODO Auto-generated method stub
        return R.layout.activity_homepagetwo;
    }

    // HomePageSecondAdapter adapter;

    // private ArrayList<GridViewBean> list = new ArrayList<GridViewBean>();

    @Override
    public void onMyActivityCreated() {
        homePagePresenter = new HomePagePresenter(this);
        homePagePresenter.appHead("" + pageSize);
        getLoginInfo();
        BasePtr.setRefreshOnlyStyle(commend_anchor_ptr);
        commend_anchor_ptr.autoRefresh(true);
        commend_anchor_ptr.setPtrHandler(new PtrDefaultHandler2() {
            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                getLoginInfo();
                homePagePresenter.appHead("" + pageSize);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getLoginInfo();
                homePagePresenter.appHead("" + pageSize);
            }
        });

    }

    private void getLoginInfo() {
        uid = SPUtils.get(getActivity(), null, SpPublicParams.UID, "") + "";
        psw = SPUtils.get(getActivity(), null, SpPublicParams.PASSWORD, "") + "";
    }

    ArrayList<HomeTypeTwoModel> arrayList2 = new ArrayList<HomeTypeTwoModel>();
    HomeTypeTwoModel homeTypeTwoModel = new HomeTypeTwoModel();

    @SuppressWarnings("deprecation")
    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity model = super.handlerError(data);
        commend_anchor_ptr.refreshComplete();
        Gson gson = new Gson();
        if (model != null) {
            if (model.getEventType() == HomePagePresenter.BannerSuccessEvent) {
                page = (AppHeadPage) model.getData();
                arrayList2.clear();
                for (int i = 0; i < page.getItem_data().size(); i++) {
                    homeTypeTwoModel = gson.fromJson(page.getItem_data().get(i)
                            .getData()
                            + "", HomeTypeTwoModel.class);
                    arrayList2.add(homeTypeTwoModel);
                }
                System.out.println(arrayList2.size() + "---------->");

                // for (int j = 0; j < page.getItem_data().size(); j++) {
                // String dataString = (String) page.getItem_data().get(j)
                // .getData();
                // try {
                // JSONObject jsonObject = new JSONObject(dataString);
                // String block_id = jsonObject.getString("block_id");
                // String block_name = jsonObject.getString("block_name");
                // JSONArray bannArray = jsonObject
                // .getJSONArray("banners");
                // for (int i = 0; i < bannArray.length(); i++) {
                // JSONObject banners = bannArray.getJSONObject(i);
                // int key = banners.getInt("key");
                // String id = banners.getString("id");
                // String name = banners.getString("name");
                // // int width = banners.getInt("width");
                // // int height = banners.getInt("height");
                // // JSONObject groupJsonObject = banners
                // // .getJSONObject("product_group");
                //
                // JSONObject grouplistJsonObject = banners
                // .getJSONObject("group_product_list");
                //
                // // String max = groupJsonObject.getString("max");
                // // ArrayList<String> product_ids =
                // // (ArrayList<String>)
                // // groupJsonObject
                // // .get("product_ids");
                //
                // // String[] pidsString = grouplistJsonObject
                // // .get("p_ids");
                //
                // // JSONArray skuArray = grouplistJsonObject
                // // .getJSONArray("sku");
                // // JSONObject skuJsonObject =
                // // skuArray.getJSONObject(0);
                // // String keyString =
                // // skuJsonObject.getString("key");
                // // String idString = skuJsonObject.getString("id");
                // // String nameString =
                // // skuJsonObject.getString("name");
                // // String skuid = skuJsonObject.getString("sku_id");
                // // String end_time =
                // // skuJsonObject.getString("end_time");
                // // String start_time =
                // // skuJsonObject.getString("start_time");
                // // String price = skuJsonObject.getString("price");
                // // String indexForSort =
                // // skuJsonObject.getString("indexForSort");
                // // String display_order = skuJsonObject
                // // .getString("display_order");
                // adtwo = id;
                // bannerNamedan2.add(name);
                // blokdan2 = block_id;
                // JSONObject producthomeObject = banners
                // .getJSONObject("product_home");
                // JSONArray productInfoArray = producthomeObject
                // .getJSONArray("product_info");
                // imagesList.clear();
                // goodsName.clear();
                // goodsPrice.clear();
                // goodsPid.clear();
                // for (int k = 0; k < productInfoArray.length(); k++) {
                // JSONObject productObject = productInfoArray
                // .getJSONObject(k);
                // String product_id = productObject
                // .getString("product_id");
                // String pname = productObject.getString("name");
                // String img = productObject.getString("img");
                // String price = productObject.getString("price");
                // goodsName.add(pname);
                // goodsPrice.add(price);
                // goodsPid.add(product_id);
                // imagesList.add(img);
                // // key.length();
                //
                // }
                //
                // }
                //
                // } catch (JSONException e) {
                // // TODO Auto-generated catch block
                // e.printStackTrace();
                // }
                // // ad_two.setScaleType(ScaleType.CENTER_CROP);
                // // showImage(adtwo, ad_two);
                //
                // }

                myListviewAdapter adapter = new myListviewAdapter(
                        getActivity(), arrayList2);
                // adtwo,goodsName.size());
                mylistview.setAdapter(adapter);
            }
        }
        commend_anchor_ptr.refreshComplete();
    }

    private void showImage(String imageid2, ImageView ad_one2) {
        // TODO Auto-generated method stub
        XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
                + imageid2, ad_one2);
    }

    class myListviewAdapter extends BaseAdapter {
        Context context;
        ArrayList<HomeTypeTwoModel> arrayList2;

        public myListviewAdapter(Context context,
                                 ArrayList<HomeTypeTwoModel> arrayList2) {
            // TODO Auto-generated constructor stub
            this.context = context;
            this.arrayList2 = arrayList2;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return arrayList2 == null ? 0 : arrayList2.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return arrayList2 == null ? 0 : position;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(final int position, View convertView,
                            ViewGroup parent) {
            // TODO Auto-generated method stub
            viewHolder holder = null;
            if (convertView == null) {
                holder = new viewHolder();
                convertView = LayoutInflater.from(context).inflate(
                        R.layout.item_homepagetypetwo, null);
                holder.ad_two = (ImageView) convertView
                        .findViewById(R.id.ad_two);
                holder.list = (LinearLayout) convertView
                        .findViewById(R.id.list);
                XPicasso.loadBigImage(context, holder.ad_two,
                        GlobalConfig.API_URL + "/picture/index?id=" + arrayList2.get(position).getBanners().get(0).getId());
                holder.ad_two.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                         getLoginInfo();
                        Intent intent2 = new Intent(getActivity(),
                                WebActivity.class);
                        intent2.putExtra("title", arrayList2.get(position).getBanners().get(0).getName());
                        intent2.putExtra("url", APP_URL
                                + "/viewPage/index/block/" + arrayList2.get(position).getBlockId()
                                + "/banner/" + 0 + "?uid=" + uid + "&psw=" + psw);
                        Log.e("hu blockid", arrayList2.get(position).getBlockId() + "");
                        startActivity(intent2);
                    }
                });
                holder.list.removeAllViews();
                if (arrayList2.get(position).getBanners().size() > 0) {
                    if (arrayList2.get(position).getBanners().get(0).getProductHome() != null) {
                        for (int m = 0; m < arrayList2.get(position).getBanners().get(0).getProductHome().getProductInfo().size(); m++) {

                            ImageView[] mimg = new ImageView[arrayList2.get(position).getBanners().get(0).getProductHome().getProductInfo().size()];
                            View view = LayoutInflater.from(getActivity()).inflate(
                                    R.layout.topview, null);
                            ImageView imageView = (ImageView) view
                                    .findViewById(R.id.hot);
                            TextView textView = (TextView) view.findViewById(R.id.tv1);
                            TextView textView2 = (TextView) view.findViewById(R.id.tv2);
                            textView.setText(arrayList2.get(position).getBanners().get(0).getProductHome().getProductInfo().get(m).getName());
                            textView2.setText("￥" + arrayList2.get(position).getBanners().get(0).getProductHome().getProductInfo().get(m).getPrice());
                            showImage(arrayList2.get(position).getBanners().get(0).getProductHome().getProductInfo().get(m).getImg(), imageView);
                            textView.setGravity(Gravity.CENTER);
                            textView.setTextColor(getResources()
                                    .getColor(R.color.black));
                            mimg[m] = imageView;
                            mimg[m].setTag(m);
                            android.widget.LinearLayout.LayoutParams lP = new android.widget.LinearLayout.LayoutParams(
                                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT,
                                    android.widget.LinearLayout.LayoutParams.WRAP_CONTENT);
                            lP.setMargins(10, 10, 10, 10);
                            holder.list.addView(view, lP);
                            mimg[m].setOnClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View v) {
                                    // TODO Auto-generated method stub
                                    Intent intent = new Intent(getActivity(),
                                            GoodsDetailActivity.class);
                                    intent.putExtra("pid",
                                            arrayList2.get(position).getBanners().get(0).getProductHome().getProductInfo().get((int) (v.getTag())).getProductId());

//											goodsPid.get((int) v.getTag()));
                                    startActivity(intent);
                                }
                            });

                        }
                    }
                }


                convertView.setTag(holder);
            } else {
                holder = (viewHolder) convertView.getTag();
            }
            return convertView;
        }
    }

    class viewHolder {
        ImageView ad_two;
        LinearLayout list;
    }
}
